// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    let checkCanJuInfo = await canJu.doc(event._id)
      .field({
        canPlay: true,
        playTime: true
      })
      .get()
    let oldTime = new Date(checkCanJuInfo.data.playTime).getTime()
    let playerTime = new Date(event.playTime).getTime()

    if (playerTime != oldTime) {
      return {
        code: 'fail',
        res: null
      }
    }
    if (checkCanJuInfo.data.canPlay) {
      return {
        code: 'fail',
        res: null
      }
    }

    const res = await canJu
      .doc(event._id)
      .update({
        data: {
          canPlay: true
        }
      })
    return {
      code: 'ok',
      res: res
    }
  } catch (e) {
    return {
      code: 'fail',
      res: null
    }
  }



}
